package com.tjy.wfx.controller;


import com.alibaba.fastjson.JSONArray;
import com.tjy.wfx.model.SysModule;
import com.tjy.wfx.model.UserInfo;
import com.tjy.wfx.service.SysModuleService;
import com.tjy.wfx.service.UserInfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserAuthorizationController {


    @Autowired
    private UserInfoService userInfoService;
    @RequestMapping("/login")
    public String login(UserInfo userInfo, Model model){
        //--------认证授权的方法
        UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUserName(), userInfo.getPassword());
        try {
            SecurityUtils.getSubject().login(token);
            //--------
            //根据用户账号,查询顶级菜单和次级菜单信息返回给前端页面
          List<SysModule>  moduleList= userInfoService.findMenu(userInfo.getUserName());
            model.addAttribute("moduleList",moduleList);
            //把用户信息传递到页面 用于做授权提交
            UserInfo user= (UserInfo) SecurityUtils.getSubject().getPrincipal();
          model.addAttribute("userInfo",user);
            return "index";
        }catch (Exception e){
            return "500";
        }
    }

    @RequestMapping("/logout")
    public String logOut(){
        SecurityUtils.getSubject().logout();
        return "redirect:/404";
    }
//    @RequestMapping("/user")
//    @RequiresRoles(value = {"user","admin"},logical = Logical.OR)
//    public String RoleUser(Model model){
//        model.addAttribute("msg","user或admin你好欢迎回来");
//        return "user";
//    }
//
//    @RequestMapping("/admin")
//    @RequiresRoles("manager")
//    public String RoleAdmin(Model model){
//        model.addAttribute("msg","admin你好欢迎回来");
//        return "admin";
//    }

    @Autowired
    private SysModuleService sysModuleService;
    @RequestMapping("/ztree")
    public String ztree(Model model){
        List<SysModule> menus = sysModuleService.findAll();
        model.addAttribute("menus", JSONArray.toJSONString(menus));
        return "ztree";
    }
}
